package com.symone.webcms.schedule;

import com.symone.webcms.model.ScheduleTask;
import com.symone.webcms.model.TaskLog;
import com.symone.webcms.service.ScheduleTaskService;
import com.symone.webcms.service.TaskLogService;
import com.symone.webcms.util.SpringUtil;
import com.symone.webcms.util.TaskUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class TaskFactory implements Job {

    protected Logger logger = LoggerFactory.getLogger(TaskFactory.class);
    @Override
    public void execute(JobExecutionContext context) {
        JobDetail job = context.getJobDetail();
        JobKey key = job.getKey();
        String jobIdentity = "scheduleJob" + key.getGroup() + "_" + key.getName();
        Trigger trigger = context.getTrigger();
        ScheduleTask scheduleJob = (ScheduleTask) context.getMergedJobDataMap().get(jobIdentity);
        logger.info("运行任务名称 = [" + scheduleJob + "]");

        try {
            TaskLog result = TaskUtil.invokMethod(scheduleJob);

            scheduleJob.setNextTime(trigger.getNextFireTime());
            scheduleJob.setPreviousTime(trigger.getPreviousFireTime());

            ScheduleTaskService taskService = (ScheduleTaskService) SpringUtil.getBean(ScheduleTaskService.class);
            taskService.updateTimeById(scheduleJob.getPreviousTime(), scheduleJob.getNextTime(), scheduleJob.getId());

            // 写入运行结果
            TaskLogService taskLogService = (TaskLogService) SpringUtil.getBean(TaskLogService.class);
            taskLogService.insert(result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}